package com.lx.pc.restful.personalcenter;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.lx.pc.domain.vo.category.CategoryVo;
import com.lx.pc.domain.vo.forbuy.ForbuyVo;
import com.lx.pc.domain.vo.goodssupply.GoodssupplyVo;
import com.lx.pc.domain.vo.goodssupplyimg.GoodssupplyimgVo;
import com.lx.pc.domain.vo.platformreplacement.PlatformreplacementVo;
import com.lx.pc.domain.vo.supplydemand.SupplydemandVo;
import com.lx.pc.domain.vo.supplydemandimg.SupplydemandimgVo;
import com.lx.pc.domain.vo.sysarea.SysareaVo;
import com.lx.pc.domain.vo.user.UserVo;
import com.lx.pc.restful.BaseController;
import com.lx.pc.restful.util.AjaxResult;
import com.lx.pc.restful.util.WebUtil;
import com.lx.pc.service.category.ICategoryService;
import com.lx.pc.service.goodssupply.IGoodssupplyService;
import com.lx.pc.service.goodssupplyimg.IGoodssupplyimgService;
import com.lx.pc.service.platformreplacement.IPlatformreplacementService;
import com.lx.pc.service.supplydemand.ISupplydemandService;
import com.lx.pc.service.supplydemandimg.ISupplydemandimgService;
import com.lx.pc.service.sysarea.ISysareaService;
import com.lx.pc.utils.ImageOperation;

@Controller
@RequestMapping("/buymanage")
public class PersonalcenterController extends BaseController{
	
	/**
	 * 类目
	 */
	@Resource(name = "categoryService")
	private ICategoryService categoryService;
	
	/**
	 * 现货
	 */
	@Resource(name = "goodssupplyService")
	private IGoodssupplyService goodssupplyService;
	
	/**
	 * 现货图片
	 */
	@Resource(name = "goodssupplyimgService")
	private IGoodssupplyimgService goodssupplyimgService;
	
	/**
	 * 地区
	 */
	@Resource(name = "sysareaService")
	private ISysareaService sysareaService;
	
	/**
	 * 求购黄页
	 */
	@Resource(name = "supplydemandService")
	private ISupplydemandService supplydemandService;
	
	/**
	 * 求购黄页图片
	 */
	@Resource(name = "supplydemandimgService")
	private ISupplydemandimgService supplydemandimgService;
	
	@Resource(name = "platformreplacementService")
	private IPlatformreplacementService platformreplacementService;
	
	/**
	 * 发布求购
	 * @return
	 */
	@RequestMapping(value = "/toPlatformbuy.do")
	public ModelAndView toPlatformbuy(HttpServletRequest request) {
		ModelAndView mv = getModelAndView("/buymanage/platformbuy",request);
		
		StringBuffer sb = toCategoryJson();
		mv.addObject("dataJson",sb);
		
		return mv;
	}
	
	/**
	 * 添加成功跳转
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/toPlatformSucces.do")
	public ModelAndView toPlatformSucces(HttpServletRequest request) {
		ModelAndView mv = getModelAndView("/buymanage/forbuy_success",request);
		
		return mv;
	}
	
	/**
	 * 添加成功
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/toPlatformbuySave.do")
	public AjaxResult<String> toPlatformbuySave(ForbuyVo v,@RequestParam(value = "imgUrl[]")String[] imgUrl,HttpServletRequest request) {
		AjaxResult<String> ajaxResult = new AjaxResult<String>();
		
		UserVo userVo = super.getUserInfo(request);
		if (v.getStatus() == 1) {//保存现货
			GoodssupplyVo goodssupplyVo = new GoodssupplyVo();
			//发布人id
			goodssupplyVo.setUserId(userVo.getId());
			//标题
			goodssupplyVo.setTitle(v.getName());
			//数量
			goodssupplyVo.setNum(v.getNum());
			//单位
			goodssupplyVo.setCompany(v.getCompany());
			//目标单位 1 电议 2 具体值
			goodssupplyVo.setTarget(v.getTarget());
			//价格
			goodssupplyVo.setPrice(v.getPrice());
			//分类Id
			goodssupplyVo.setCategoryId(v.getCategoryId());
			//分类Id
			List<String> list = new ArrayList<String>();
			for (String category : v.getCategoryId().split(",")) {
				list.add(category);
			}
			
			if (list.size() == 2) {
				goodssupplyVo.setCategoryId(list.get(1));
				goodssupplyVo.setCategoryLevel(list.get(0));
			}else {
				goodssupplyVo.setCategoryId(list.get(1));
				goodssupplyVo.setCategoryLevel(list.get(2));
			}
			
			//收货地址 根据详细地址查询省
			JSONObject jsonObject = WebUtil.getAddress(v.getAddress());
			if (jsonObject != null) {
				String province = (String) jsonObject.get("province");
				SysareaVo area = new SysareaVo();
				area.setName(province);
				SysareaVo sysareaVo = sysareaService.findBySerchSysarea(area);
				goodssupplyVo.setProvince(sysareaVo.getAreaCode());
			}
			
			//详细地址
			goodssupplyVo.setAddress(v.getAddress());
			
			//运送方式 1 送货上门 2 上门自提
			goodssupplyVo.setMode(v.getMode());
			//报价截止日期 有效期
			goodssupplyVo.setDeadline(v.getEndTime());
			//账单要求 1 货到付款 2 可接受账期
			goodssupplyVo.setBill(v.getBill());
			//发票要求 1 可提供发票 2 无需求
			goodssupplyVo.setInvoice(v.getInvoice());
			//所在地要求
			goodssupplyVo.setLocationAddress(v.getLocationAddress());
			//说明
			goodssupplyVo.setExplainContent(v.getExplain());
			//货物描述
			goodssupplyVo.setContent(v.getContent());
			//类型 1 现货供应 2 现货求购
			goodssupplyVo.setType("2");
			
			goodssupplyService.save(goodssupplyVo);
			
			//货物图片
			for (String strImg : imgUrl) {
				GoodssupplyimgVo goodssupplyimgVo = new GoodssupplyimgVo();
				goodssupplyimgVo.setGoodsSupplyId(goodssupplyVo.getId());
				String url = request.getSession().getServletContext().getRealPath("/")+("/fileImage/");
				if (strImg.equals("data:image/png;base64") || 
					strImg.equals("data:image/jpeg;base64") ||
					strImg.equals("data:image/gif;base64") ||
					strImg.equals("data:image/jpg;base64")) {
					continue;
				}
				String img = ImageOperation.encode64Image(strImg, url);
				if (img != null && img !="") {
					goodssupplyimgVo.setImg(img);
					goodssupplyimgService.save(goodssupplyimgVo);
				}
			}
			
		}else if (v.getStatus() == 2) { //保存黄页
			SupplydemandVo supplydemandVo = new SupplydemandVo();
			//发布人id
			supplydemandVo.setUserId(userVo.getId().toString());
			//标题
			supplydemandVo.setTitle(v.getName());
			//数量
			supplydemandVo.setNum(v.getNum());
			//单位
			supplydemandVo.setCompany(v.getCompany());
			//目标单位 1 电议 2 具体值
			supplydemandVo.setTarget(v.getTarget());
			//价格
			supplydemandVo.setPrice(v.getPrice());
			//分类Id
			List<String> list = new ArrayList<String>();
			for (String category : v.getCategoryId().split(",")) {
				list.add(category);
			}
			
			if (list.size() == 2) {
				supplydemandVo.setCategoryId(list.get(1));
				supplydemandVo.setCategoryLevel(list.get(0));
			}else {
				supplydemandVo.setCategoryId(list.get(1));
				supplydemandVo.setCategoryLevel(list.get(2));
			}
			
			//收货地址 根据详细地址查询省
			JSONObject jsonObject = WebUtil.getAddress(v.getAddress());
			if (jsonObject != null) {
				String province = (String) jsonObject.get("province");
				SysareaVo sysarea = new SysareaVo();
				sysarea.setName(province);
				SysareaVo sysareaVo = sysareaService.findBySerchSysarea(sysarea);
				supplydemandVo.setProvince(sysareaVo.getAreaCode());
			}
			//详细地址
			supplydemandVo.setAddress(v.getAddress());
			
			//运送方式 1 送货上门 2 上门自提
			supplydemandVo.setMode(v.getMode());
			
			//报价截止日期 有效期
			supplydemandVo.setDeadline(v.getEndTime());
			
			//货物描述
			supplydemandVo.setContent(v.getContent());
			
			//类型 1 黄页供应 2 黄页求购,
			supplydemandVo.setType("2");
			
			supplydemandService.save(supplydemandVo);
			
			//货物图片
			for (String strImg : imgUrl) {
				SupplydemandimgVo supplydemandimgVo = new SupplydemandimgVo();
				supplydemandimgVo.setSupplyDemandId(supplydemandVo.getId().toString());
				String url = request.getSession().getServletContext().getRealPath("/")+("/fileImage/");
				if (strImg.equals("data:image/png;base64") || 
						strImg.equals("data:image/jpeg;base64") ||
						strImg.equals("data:image/gif;base64") ||
						strImg.equals("data:image/jpg;base64")) {
						continue;
				}
				String img = ImageOperation.encode64Image(strImg, url);
				
				supplydemandimgVo.setImg(img);
				supplydemandimgService.save(supplydemandimgVo);
			}
			
		}else {
			PlatformreplacementVo platformreplacementVo = new PlatformreplacementVo();
			//发布人id
			platformreplacementVo.setUserId(userVo.getId());
			//标题
			platformreplacementVo.setTitle(v.getName());
			//数量
			platformreplacementVo.setNum(v.getNum());
			//单位
			platformreplacementVo.setCompany(v.getCompany());
			//目标单位 1 电议 2 具体值
			platformreplacementVo.setTarget(v.getTarget());
			//价格
			platformreplacementVo.setPrice(v.getPrice());
			//分类Id
			platformreplacementVo.setCategoryId(v.getCategoryId());
			//分类Id
			List<String> list = new ArrayList<String>();
			for (String category : v.getCategoryId().split(",")) {
				list.add(category);
			}
			
			if (list.size() == 2) {
				platformreplacementVo.setCategoryId(list.get(1));
				platformreplacementVo.setCategoryLevel(list.get(0));
			}else {
				platformreplacementVo.setCategoryId(list.get(1));
				platformreplacementVo.setCategoryLevel(list.get(2));
			}
			
			//收货地址 根据详细地址查询省
			JSONObject jsonObject = WebUtil.getAddress(v.getAddress());
			if (jsonObject != null) {
				String province = (String) jsonObject.get("province");
				SysareaVo sysarea = new SysareaVo();
				sysarea.setName(province);
				SysareaVo sysareaVo = sysareaService.findBySerchSysarea(sysarea);
				platformreplacementVo.setProvince(sysareaVo.getAreaCode());
			}
			//详细地址
			platformreplacementVo.setAddress(v.getAddress());
			
			//运送方式 1 送货上门 2 上门自提
			platformreplacementVo.setMode(v.getMode());
			//报价截止日期 有效期
			platformreplacementVo.setDeadline(v.getEndTime());
			//账单要求 1 货到付款 2 可接受账期
			platformreplacementVo.setBill(v.getBill());
			//发票要求 1 可提供发票 2 无需求
			platformreplacementVo.setInvoice(v.getInvoice());
			//类型 1 平台代买 2 平台代卖
			platformreplacementVo.setType("1");
			
			platformreplacementService.save(platformreplacementVo);
		}
		
		ajaxResult.setMsg("1");
		return ajaxResult;
	}
	
	/**
	 * 类目拼接成json
	 * @return
	 */
	public StringBuffer toCategoryJson() {
		
		StringBuffer sbBuffer = new StringBuffer();
		sbBuffer.append("{\"option\":[");
		
		CategoryVo category = new CategoryVo();
		category.setParentId("0");
		category.setActive((short) 1);
		category.setStatus(1);
		//一级类目
		List<CategoryVo> categoryList = categoryService.findByCategoryList(category);
		if (categoryList.size() > 0) {
			for (CategoryVo categoryVo : categoryList) {
				sbBuffer.append("{");
				sbBuffer.append("\"id\":\""+categoryVo.getCategoryId()+"\",");
				sbBuffer.append("\"name\":\""+categoryVo.getName()+"\",");
				
				category.setParentId(categoryVo.getCategoryId());
				List<CategoryVo> categoryTwoList = categoryService.findByCategoryList(category);
				if (categoryTwoList.size() > 0) {
					sbBuffer.append("\"child\": [");
					//查询二级类目
					for (CategoryVo categoryTwo : categoryTwoList) {
						
						sbBuffer.append("{");
						sbBuffer.append("\"id\":\""+categoryTwo.getCategoryId()+"\",");
						sbBuffer.append("\"name\":\""+categoryTwo.getName()+"\",");
						
						//查询三级类目
						category.setParentId(categoryTwo.getCategoryId());
						List<CategoryVo> categoryThreeList = categoryService.findByCategoryList(category);
						if (categoryThreeList.size() > 0) {
							sbBuffer.append("\"child\": [");
							for (CategoryVo categoryThree : categoryThreeList) {
								sbBuffer.append("{");
								sbBuffer.append("\"id\":\""+categoryThree.getCategoryId()+"\",");
								sbBuffer.append("\"name\":\""+categoryThree.getName()+"\",");
								sbBuffer.append("},");
							}
							sbBuffer = sbBuffer.deleteCharAt(sbBuffer.length()- 1);
							sbBuffer.append("]");
						}
						sbBuffer.append("},");
					}
					sbBuffer = sbBuffer.deleteCharAt(sbBuffer.length()- 1);
					sbBuffer.append("]");
				}
				sbBuffer.append("},");
			}
			sbBuffer = sbBuffer.deleteCharAt(sbBuffer.length()- 1);
			sbBuffer.append("]}");
		}
		
		return sbBuffer;
	}
	
	
	
}
